import oracledb from 'oracledb'
import mysql from 'mysql'
// import constant from '../../common/global-constant'

const getOracleConnection = async (dbInfo) => {
    let connection
    try {
        connection = await oracledb.getConnection({
            user: dbInfo.username,
            password: dbInfo.password,
            connectString: dbInfo.connectionStr
        });
        console.log("Successfully connected to Oracle!")
        return connection;
    } catch (err) {
        throw Error(err);
    }
}

const getMysqlConnection = (dbInfo) => {
    let connection
    try {
        connection = mysql.createConnection({
            host: dbInfo.host,
            user: dbInfo.username,
            password: dbInfo.password,
            database: dbInfo.initDb,
        });
        console.log("Successfully connected to Mysql!")
        return connection;
    } catch (err) {
        throw Error(err);
    }
}



const getConnection = async (dbInfo) => {
    switch (dbInfo.type) {
        case 0:
            return getMysqlConnection(dbInfo)
        case 2:
            return await getOracleConnection(dbInfo)
        default:
            throw Error(`未知的数据库类型:${dbInfo.type}`);
    }
}

const run = async (conn, sql) => {
    return new Promise((success, error) => {
        conn.query(sql, (err, result) => {
            if (err) {
                throw Error(`运行错误:${JSON.stringify(err)}`);
            }
            success(result);
        })
    })
}


export default {
    runSql: async ({
        sql,
        dbInfo
    }) => {
        let conn = await getConnection(dbInfo)
        let res
        debugger
        res = await run(conn, sql) // conn.query(sql);
        conn.end() //关闭连接


        //oralce
        //  res = await conn.execute(sql, [], {});
        // debugger
        // //关闭连接
        // if (conn) {
        //     try {
        //         await conn.close();
        //     } catch (err) {
        //         console.log("Error when closing the database connection: ", err);
        //     }
        // }
        return res;
    }
}